package com.atguigu.spzx.manager.interceptor;

import com.alibaba.fastjson.JSON;
import com.atguigu.spzx.model.pojo.system.SysUser;
import com.atguigu.spzx.model.pojo.system.SysUserAuthContextUtil;
import com.atguigu.spzx.utils.DYLAssert;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * @author dyl
 * @version 1.0
 * @description: 查询当前用户信息拦截器
 * @date 2024/12/26 21:57
 */
@Component
public class LoginAuthInterceptor implements HandlerInterceptor {
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("拦截器拦截");
        //先处理option请求
        if (request.getMethod().equals("OPTIONS")) {
            return true;
        }

        // 从redis中获取当前用户信息
        String token = request.getHeader("token");
        DYLAssert.notNull(token, "拦截器错误token");
        String JSONUser = redisTemplate.opsForValue().get("user:login:" + token);
        DYLAssert.notNull(JSONUser, "拦截器错误userInfo");
        SysUser user = JSON.parseObject(JSONUser, SysUser.class);

        // 将当前用户信息存入线程存储空间中
        SysUserAuthContextUtil.set(user);
        return true;
    }
}
